package com.yutel.gps.server;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yutel.gps.dao.TableDBDao;
import com.yutel.gps.http.BaiduGps;
import com.yutel.gps.model.LocationsNode;
import com.yutel.gps.model.RunParameter;

public class Convert implements Runnable {
	private final Logger log = LoggerFactory.getLogger(Convert.class);

	private TableDBDao oDao;
	private Gps gps;
	private LocationsNode old;

	public Convert() {
		oDao = new TableDBDao();
		gps = new BaiduGps();
	}

	public void start() {
		log.info("start convert");
		run();
	}

	public void destroy() {
		oDao.destroy();
	}

	public void run() {
		while (true) {
			try {
				List<LocationsNode> list = oDao.query();
				if (list.size() == 0) {
					log.error("convert finish");
					break;
				}
				for (LocationsNode ln : list) {
					if (ln.equal(old)) {
						log.warn("the same data is ignore");
						continue;
					}
					LocationsNode res = gps.convert(ln);
					if (res != null) {
						int s = oDao.save(ln);
						if (s == 0) {
							log.error("data save fail");
						}
						old = res;
					}
					Thread.sleep(RunParameter.getIns().getFrequency());
				}
				log.info("converted count {}", list.size());
			} catch (Exception e) {
				log.error("run", e);
			}
		}
	}

}
